/*
// import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
// import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      // '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})
*/
import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vite/plugins'
import autoprefixer from 'autoprefixer'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV } = env
  return {
    base: VITE_APP_ENV === 'production' ? '/' : '/',
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src')
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    // vite 相关配置
    server: {
      port: 8080,
      host: true,
      open: true,
      proxy: {
        '/dev-api': {
          target: 'http://10.11.3.94:9998',
          // target: 'http://192.168.69.46:8080',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, '')
          // 测试环境
          // rewrite: (p) => p.replace(/^\/dev-api/, '/bitnei-energy'),
        }
      }
    },
    build: {
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash][extname]',
          manualChunks: (id, { getModuleInfo, getModuleIds }) => {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        }
      }
    },
    esbuild: {
      //清除全局的console.log和debug
      drop: VITE_APP_ENV === 'production' ? ['console', 'debugger'] : []
    },
    //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
      modules: {
        localsConvention: 'camelCase'
      },
      preprocessorOptions: {
        // less: {
        //   additionalData: '@import "@/assets/style/constant.less";'
        // }
        scss: {
          api: 'modern'
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          },
          autoprefixer
        ]
      },
      // 在开发过程中是否启用 sourcemap。
      devSourcemap: true
    }
  }
})
